package com.fckbug.action.upload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.fckbug.Constants;
import com.fckbug.util.WebappUtil;
import com.fckbug.vos.Acc;

public class UploadPhotoAction extends Action {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		MyForm uploadForm = (MyForm) form;
		FormFile file = uploadForm.getMyfile();
		Acc acc = WebappUtil.getLoginUser(request);
		String result = "[0]";
		try {
			File outputFile = new File(Constants.UPLOAD_PATH+acc.getId()+File.separator+"head"+File.separator+"head.jpg");
			if(outputFile.exists()) {
				outputFile.delete();
			} else {
				outputFile.mkdirs();
			}
			InputStream is = file.getInputStream();
			OutputStream os = new FileOutputStream(outputFile);
			int size = 0;
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
				size = size + bytesRead;
				os.write(buffer, 0, bytesRead);
			}
			os.flush();
			os.close();
			is.close();
			result = "FILEID:" + acc.getId();
		} catch(Exception ex) {
			ex.printStackTrace();
		}
		try {
			PrintWriter pw = response.getWriter();
			pw.print(result);
		} catch(Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}
}
